package com.lyhengtongwl.zqsnews.widget;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentManager;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.base.Constant;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.net.ShareCallBack;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.ui.activity.MainActivity;
import com.lyhengtongwl.zqsnews.ui.activity.QCInvitationActivity;
import com.lyhengtongwl.zqsnews.utils.AppConfig;
import com.lyhengtongwl.zqsnews.utils.CheckApkExist;
import com.lyhengtongwl.zqsnews.utils.CopyUtils;
import com.lyhengtongwl.zqsnews.utils.DesUtils;
import com.lyhengtongwl.zqsnews.utils.NewsOpenShare;
import com.lyhengtongwl.zqsnews.utils.SPUtils;


import me.shaohui.bottomdialog.BottomDialog;
import retrofit2.Response;

public class NewsShare {
    private static String mTitle;
    private static String mImgUrl;

    public static void showShareDialog(FragmentManager manager, Activity activity, String articleId,
                                       String title, String imgUrl
    ) {
        mTitle = title;
        mImgUrl = imgUrl;
        try {
            String baseUrl = AppConfig.getInstance(App.getContext()).get("transfer_articleShareUrl");
            String userId = SPUtils.get(App.getContext(), "random_code", "") + "";
//            String url = baseUrl + "?articleId=" + articleId + "&userId=" + userId + "&t=" + System.currentTimeMillis();

            //测试使用
            String testParam = "articleId=" + articleId + "&userId=" + userId + "&t=" + System.currentTimeMillis();
            String url = baseUrl + "?s=" + DesUtils.desEncrypt(testParam);
            //测试使用
            final BottomDialog bottomDialog;
            bottomDialog = BottomDialog.create(manager);
            bottomDialog.setViewListener(new BottomDialog.ViewListener() {
                @Override
                public void bindView(View v) {
                    //微信
                    (v.findViewById(R.id.ll_wc)).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //微信好友分享
                            bottomDialog.dismiss();
//                        NewsShareUtils.shareUrlToFriends(activity, articleShareEntity.getTitle(), url, articleShareEntity.getImgUrl()
//                        );

                            new NewsOpenShare(activity).ShareUrlToWx(mTitle, url, mImgUrl, baseUrl, 0);
                        }
                    });
                    (v.findViewById(R.id.ll_wcc)).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //微信朋友圈
                            bottomDialog.dismiss();
                            new NewsOpenShare(activity).ShareUrlToWx(mTitle, url, mImgUrl, baseUrl, 1);
//                        NewsShareUtils.shareUrlToCircleFriends(activity, articleShareEntity.getTitle(), url, articleShareEntity.getImgUrl());
                        }
                    });
                    (v.findViewById(R.id.iv_close)).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //关闭
                            bottomDialog.dismiss();
                        }
                    });
                    (v.findViewById(R.id.ll_copyUrl)).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //复制短连接 进行复制并跳转微信
                            toShortChain(activity,url);
                        }
                    });
                    String str = AppConfig.getInstance(App.getContext()).get("QQBrowserTip");
                    if ("".equals(str)) {
                        (v.findViewById(R.id.ll_browser)).setVisibility(View.GONE);
                    } else {
                        (v.findViewById(R.id.ll_browser)).setVisibility(View.VISIBLE);
                        TextView tv = v.findViewById(R.id.tv_browser);
                        CharSequence charSequence = Html.fromHtml(str);
                        tv.setText(charSequence);
                    }
                    (v.findViewById(R.id.ll_browser)).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //打开手机QQ浏览器
//                        articleShareEntity.getUserId()
                            String qqBrowserUrl = AppConfig.getInstance(App.getContext()).get("shareQQUrl") + "?articleId=" + articleId + "&userId=" + userId;
                            if (CheckApkExist.checkApkExist(activity, "com.tencent.mtt")) {
                                Intent intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(qqBrowserUrl);
                                intent.setData(content_url);
                                intent.setClassName("com.tencent.mtt", "com.tencent.mtt.MainActivity");
                                activity.startActivity(intent);
                            } else {
                                Uri uri = Uri.parse("market://details?id=com.tencent.mtt");//id为包名
                                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                activity.startActivity(it);
//                            Toast.makeText(App.getContext(), "您还未安装QQ浏览器，快去下载安装吧~！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }).setLayoutRes(R.layout.item_share_layout)//news_share
                    .setDimAmount(0.4f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                    .setCancelOutside(true)     // click the external area whether is closed, default is : true
                    .setTag("BottomDialog")     // setting the DialogFragment tag
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //生成短连接
    private static void toShortChain(Activity activity,String url){
        Task.getApiService().shortChain(url).enqueue(new ShareCallBack<NewsBaseEntity>(activity,url) {
            @Override
            protected void onNetFail(String url) {
                CopyUtils.copyText2(App.getContext(), mTitle + url);
                new CenterDialog(R.layout.item, activity).showSharePrompt("短链已复制，可直接复制到朋友圈或微信好友");
            }

            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                assert response.body() != null;
                String str= (String) response.body().getData();
                CopyUtils.copyText2(App.getContext(), mTitle + str);
                new CenterDialog(R.layout.item, activity).showSharePrompt("短链已复制，可直接复制到朋友圈或微信好友");
            }

            @Override
            protected void onFailure(Throwable t) {
                CopyUtils.copyText2(App.getContext(), mTitle + url);
                new CenterDialog(R.layout.item, activity).showSharePrompt("短链已复制，可直接复制到朋友圈或微信好友");
            }
        });
    }


    public static void showShareDialog_1(FragmentManager manager, Activity activity) {

        final BottomDialog bottomDialog;
        bottomDialog = BottomDialog.create(manager);
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                //微信
                (v.findViewById(R.id.ll_wcInvitation)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //微信分享
                        bottomDialog.dismiss();
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (App.hbList != null && App.hbList.size() > 0) {
//                                    Bitmap bitmapFormResources = ImgHelper.getBitmapFormResources(activity, R.mipmap.red_packet);
//                                    NewsShareUtils.shareUrlToFriends(activity, "欢迎来到赚钱树"
//                                            , Url.H5BaseUrl + "/ht/webLogin.html?shareCode=" + SPUtils.get(App.getContext(), "shareCode", ""), bitmapFormResources);
//                                }
//                            }
//                        }).start();
                        new NewsOpenShare(activity).ShareUrlToWx(Constant.ShareDetail, AppConfig.getInstance(App.getContext()).get("redBagUrl") + "?shareCode=" + SPUtils.get(App.getContext(), "shareCode", ""), R.mipmap.red_packet, AppConfig.getInstance(App.getContext()).get("redBagUrl"), 0);
                    }
                });
                (v.findViewById(R.id.ll_QrCodeInvitation)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //二维码邀请
                        bottomDialog.dismiss();
                        activity.startActivity(new Intent(activity, QCInvitationActivity.class));
                    }
                });
                (v.findViewById(R.id.ll_wccInvitation)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //微信分享
                        bottomDialog.dismiss();
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (App.hbList != null && App.hbList.size() > 0) {
//                                    Bitmap bitmapFormResources = ImgHelper.getBitmapFormResources(activity, R.mipmap.red_packet);
//                                    NewsShareUtils.shareUrlToCircleFriends(activity, "欢迎来到赚钱树"
//                                            , Url.H5BaseUrl + "/ht/webLogin.html?shareCode=" + SPUtils.get(App.getContext(), "shareCode", ""), bitmapFormResources);
//                                }
//                            }
//                        }).start();
                        new NewsOpenShare(activity).ShareUrlToWx(Constant.ShareDetail, AppConfig.getInstance(App.getContext()).get("redBagUrl") + "?shareCode=" + SPUtils.get(App.getContext(), "shareCode", ""), R.mipmap.red_packet, AppConfig.getInstance(App.getContext()).get("redBagUrl"), 1);
                    }
                });
                (v.findViewById(R.id.iv_close)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //微信分享
                        bottomDialog.dismiss();
                    }
                });
            }
        }).setLayoutRes(R.layout.item_share_enligthten)
                .setDimAmount(0.4f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                .setCancelOutside(true)     // click the external area whether is closed, default is : true
                .setTag("BottomDialog")     // setting the DialogFragment tag
                .show();
    }
}
